<?

class Smutty_Model_Transaction {

	var $models, $errors;

	/**
	 *  constructor
	 *
	 */

	function Smutty_Model_Transaction() {
		$this->models = array();
		$this->errors = array();
	}

	/**
	 *  adds one or more models to the transaction
	 *
	 *  @param [variable] model objects
	 *
	 */

	function add( &$model ) {
		$this->models[] =& $model;
	}

	/**
	 *  checks if all the models in the transaction are valid
	 *
	 *  @return boolean
	 *
	 */

	function isValid() {

		// check models for errors
		$this->errors = array();
		// NEED to use "for" not "foreach" cause of refs
		for ( $i=0; $i<sizeof($this->models); $i++ )
			if ( !$this->models[$i]->isValid() )
				$this->errors = array_merge( $this->errors, $this->models[$i]->getErrors() );

		// set errors on current controller
		$controller =& Smutty_Controller::getCurrentController();
		$controller->set( 'errors', $this->errors );

		return ( !$this->errors );

	}

	/**
	 *  checks all the models in the transaction for validity
	 *  before saving them.
	 *
	 *  @return boolean
	 *
	 */

	function save() {
		if ( !$this->isValid() )
			return false;
		// NEED to use "for" not "foreach" cause of refs
		for ( $i=0; $i<sizeof($this->models); $i++ )
			$this->models[$i]->save();
		return true;
	}

	/**
	 *  returns any errors found when trying to save the transaction
	 *
	 */

	function getErrors() {
		return $this->errors;
	}

}

?>